package com.sinodata.bsm.cicp.finder.sco;

/**
 * 文件系统发现程序. 
 * 程序返回：所属逻辑卷设备，挂载点
 */
import java.io.BufferedReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.log4j.Logger;

import com.sinodata.bsm.cicp.util.CommandReader;

public class ScoFS extends ScoFinder {
    private static final Logger logger = Logger.getLogger(ScoFS.class);
    private static final String SHELL = "df -iv |grep dev ";

    @SuppressWarnings("unchecked")
    @Override
    public List<String[]> find(String ip, Map params) {
        List<String[]> list = new ArrayList<String[]>();
        String[] fsRes = null;
        BufferedReader reader = null;
        String strLine = null;
        try {
            reader = CommandReader.getReader(ip, SHELL, 0, 0);
            //# df -iv
            //Mount Dir  Filesystem           blocks   used   free %used iused ifree %iused
            ///          /dev/root            15721636 3086204 12635432  20%  53080 1912128 3%
            ///stand     /dev/boot             30720  17416  13304  57%     16  3824    1%
            String ptnStr = "(/.*)\\s+(/dev/.*)\\s+(\\d+)\\s+(\\d+)\\s+(\\d+)\\s+(\\d+)%\\s+(\\d+)\\s+(\\d+)\\s+(\\d+)%\\s*(.*)";
            Pattern pattern = Pattern.compile(ptnStr);
            while ((strLine = reader.readLine()) != null) {
                Matcher matcher = pattern.matcher(strLine);
                if (matcher.find()) {
                    int size = 0;
                    try {
                        size = Integer.parseInt(matcher.group(3));
                    } catch (Exception e) {
                    }
                    if (size > 0) {
                        fsRes = new String[5];
                        list.add(fsRes);
                        fsRes[0] = matcher.group(2).trim();
                        fsRes[1] = matcher.group(2).trim();
                        fsRes[2] = getHostName(ip) + " " + matcher.group(2).trim();
                        fsRes[3] = matcher.group(2).trim(); //所属逻辑卷设备
                        fsRes[4] = matcher.group(1).trim(); //挂载点
                    }
                }
            }
            return list;
        } catch (IOException e) {
            logger.error("failed to get ScoFS ", e);
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    logger.error("failed to close reader", e);
                }
            }
        }
        return null;
    }
}
